﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

using AutoTestEntry.SpecificUtility;

namespace AutoTestEntry.UI
{
    public partial class MainForm : Form
    {
       // private TestEnvConfig testEnvConfig;
        private EnvDepoly envDeploy;
        private TestRunner testRunner;

        private String testAccount;
        private bool useSandBox;

        #region Init
        public MainForm()
        {
			EnvInitializer.ReadGlobalInfo();
            InitializeComponent();
            Init();
            HideDetails();
        }

        private void Init()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;

            btnSvnYes.Checked = true;
            btnEnvOnline.Checked = true;
            btnAccountAutoTest2.Checked = true;

            btnDeploy.Click += btnDeploy_Click;
            btnRun.Click += btnRun_Click;
            btnDetails.Click += btnDetails_Click;
			
            btnAccountAutoTest2.CheckedChanged += TestAccountChangedEventHandler;
            btnAccountAutoTest3.CheckedChanged += TestAccountChangedEventHandler;

            btnEnvSandBox.CheckedChanged += TestEnvChangedEventHandler;
            btnEnvOnline.CheckedChanged += TestEnvChangedEventHandler;
            btnEnvStub.CheckedChanged += TestEnvChangedEventHandler;

            btnFtpConfig.Click += btnFtpConfig_Click;

          //  testEnvConfig = new TestEnvConfig();

            envDeploy = new EnvDepoly();
            envDeploy.NewInfoEvent += DeployNewInfoEventHandler;
			envDeploy.LastLineChangedEvent += LastLineChangedEventHandler;
			envDeploy.AutoDeployFinishedEvent += AutoDeployFinishedEventHandler;

            testRunner = new TestRunner();
            testRunner.NewInfoEvent += RunNewInfoEventHander;
			testRunner.ErrorSVNPasswdEvent += ErrorSVNPasswdEventHandler;

            testAccount = "AutoTest2";
            useSandBox = false;

			this.Shown += MainForm_Shown;

			bgDownloadWorker.DoWork += bgDownloadWorker_DoWork;
			bgDownloadWorker.RunWorkerCompleted += bgDownloadWorker_RunWorkerCompleted;

			this.Text = this.Text + " " + envDeploy.GetVersion();
        }

		private void MainForm_Shown(Object sender, EventArgs e)
		{
			// check the ftp address and new version
			FtpConfigForm form = new FtpConfigForm(true);
			DialogResult result = form.ShowDialog();
			if (result != DialogResult.Yes)
			{
				return;
			} 
			
			String version = EnvInitializer.IsNewVersionAvailable();
			if (!String.IsNullOrEmpty(version))	// new version available
			{
				// TODO
				DialogResult res = MessageBox.Show(version + "可供下载，是否更新？", "版本更新", MessageBoxButtons.YesNo);
				if (res == DialogResult.Yes)
				{
					//启动更新程序,防止路径中有空格
					String path = "\"" + envDeploy.GetLocalUpdateExePath() + "\"";
					String curPath = "\"" + System.Windows.Forms.Application.ExecutablePath + "\"";
					String versionPath = "\"" + envDeploy.GetFtpNewVersionPath() + "\"";
 					try
					{
						System.Diagnostics.Process.Start(path,curPath + " " + versionPath);
					}
					catch
					{
						return;
					}
					this.Dispose();
				}
			}
		}

        #endregion

        #region Details
        private void btnDetails_Click(Object sender, EventArgs e)
        {
            if (btnDetails.Text == "隐藏详情")
            {
                HideDetails();
            }
            else
            {
                ShowDetails();
            }
        }

        private void ShowDetails()
        {
            this.Height = 570;
            btnDetails.Text = "隐藏详情";
        }

        private void HideDetails()
        {
            this.Height = 355;
            btnDetails.Text = "显示详情";
        }
        #endregion

        #region Display Info
        private delegate void AppendTextCallback(String text);
        private void AppendText(String text)
        {
            if (txtDetails.InvokeRequired)
            {
                AppendTextCallback d = new AppendTextCallback(AppendText);
                txtDetails.Invoke(d, text);
            }
            else
            {
                txtDetails.AppendText(text);
            }
        }
		private delegate void ChangeLastLineCallback(String text);
		private void ChangeLastLine(String text)
		{
			if (txtDetails.InvokeRequired)
			{
				ChangeLastLineCallback d = new ChangeLastLineCallback(ChangeLastLine);
				txtDetails.Invoke(d, text);
			}
			else
			{
				String[] contents = txtDetails.Text.Split(new String[] { Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
				contents[contents.Length-1] = text;

				String newContent = "";
				for (int i = 0; i < contents.Length; ++i )
				{
					newContent += contents[i] + Environment.NewLine;
				}
				txtDetails.Text = newContent;
			}
		}


        private void DeployNewInfoEventHandler(Object sender, EnvDepoly.NewInfoEventArgs e)
        {
            AppendText(e.Info);
        }

		private void LastLineChangedEventHandler(Object sender, EnvDepoly.LastLineChangedEventArgs e)
		{
			ChangeLastLine(e.Info);
			//AppendText(e.Info);
		}

		private void AutoDeployFinishedEventHandler(Object sender, EventArgs e)
		{
			MessageBox.Show("自动化部署完成");
		}

        private void RunNewInfoEventHander(Object sender, TestRunner.NewInfoEventArgs e)
        {
            AppendText(e.Info);
        }
		private void ErrorSVNPasswdEventHandler(Object sender, EventArgs e)
		{
			SVNLoginForm form = new SVNLoginForm();
			DialogResult result = form.ShowDialog();
			if (result == DialogResult.Yes)
			{
				btnRun_Click(this, null);
			}
		}
        #endregion

		#region Config Test Environment
		private void TestAccountChangedEventHandler(Object sender, EventArgs e)
		{
			if (btnAccountAutoTest2.Checked)
			{
				testAccount = "AutoTest2";
			}
			else
			{
				testAccount = "AuoteTest3";
			}
		}

		private void TestEnvChangedEventHandler(Object sender, EventArgs e)
		{
			if (btnEnvSandBox.Checked)
			{
				useSandBox = true;
			}
			else
			{
				useSandBox = false;
			}
		}
		#endregion

        #region Deploy Environment
        private void btnDeploy_Click(Object sender, EventArgs e)
        {
            txtDetails.Clear();
            if (envDeploy.CheckEnvironment())
            {
				DialogResult msgResult = MessageBox.Show("是否重新部署？", "部署", MessageBoxButtons.YesNo);
				if (msgResult == DialogResult.Yes)
				{
					EnvSettingsForm form = new EnvSettingsForm(envDeploy.GetEnvrinment());
					form.ShowDialog();
				}
            }
            else
            {
				DialogResult msgResult = (new DeploySelectionForm()).ShowDialog();
                if (msgResult == DialogResult.Yes)
                {
                    //ShowDetails();
                   // envDeploy.AutoDeploy();
					bgDownloadWorker.RunWorkerAsync();
                }
                else if (msgResult == DialogResult.No)
                {
					EnvSettingsForm form = new EnvSettingsForm(envDeploy.GetEnvrinment());
					form.ShowDialog();
                }
                else if (msgResult == DialogResult.OK)
				{
					OpenFileDialog dialog = new OpenFileDialog();
					dialog.Filter = "批处理文件 .bat|*.bat";
					if (dialog.ShowDialog() == DialogResult.OK)
					{
						String[] envs = envDeploy.GetEnvrinmentFromBat(dialog.FileName);
						if (!envDeploy.ImportSettings(envs))
						{
							EnvSettingsForm form = new EnvSettingsForm(envs);
							form.ShowDialog();
						}
						else
						{
							MessageBox.Show("部署成功");
						}
					}
                }

            }
        }

		private void bgDownloadWorker_DoWork(Object sender, DoWorkEventArgs e)
		{
			bool available = true;
			//check if the ftp is available
			String version = EnvInitializer.CheckForNewVersion();
			if (version == null)
			{
				available = false;
				if ((new FtpConfigForm(false)).ShowDialog() == DialogResult.Yes)
				{
					available = true;
				}	
			}
			
			if (available)
			{
				ShowDetails();
				envDeploy.AutoDeploy();
			}
		}

		private void bgDownloadWorker_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
		{
		}

        private void btnFtpConfig_Click(Object sender, EventArgs e)
        {
            new FtpConfigForm(false).ShowDialog();
        }

        #endregion

        #region Run Test
        private void btnRun_Click(Object sender, EventArgs e)
        {
            txtDetails.Clear();
            if (envDeploy.CheckEnvironment())
            {
                ShowDetails();

                //testEnvConfig.SetTestEnvironment(useSandBox, testAccount);

				testRunner.AutoRun(btnSvnYes.Checked, useSandBox, testAccount);
            }
            else
            {
                MessageBox.Show("请先部署环境");
                return;
            }
        }
        #endregion
    }
}
